﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web;
using Akabana.Amf.Amf3.IO;
using Akabana.Amf.Amf3.Serializer;
using Akabana.Amf.IO;
using Akabana.Amf.Serializer;

namespace Akabana.Amf.Messaging.Messages
{
    public class CommandMessage : AsyncMessage
    {

        public uint operation { get; set; }
        
        public override AcknowledgeMessage CreateAcknowledgeMessage(object body)
        {
            var result = base.CreateAcknowledgeMessage(body);

            var headers_ = new Dictionary<String, Object>();

            var session = HttpContext.Current.Session;

            var dsId = session["DSId"];
            if (dsId == null)
            {
                dsId = Guid.NewGuid().ToString().ToUpper();
                session["DSId"] = dsId;
            }

            headers_["DSId"] = dsId;
            if( this.headers.ContainsKey("DSMessagingVersion")){
                headers_["DSMessagingVersion"] = this.headers["DSMessagingVersion"];
            }
            result.headers = headers_;

            var commandClientId = session["commandClientId"];
            if (commandClientId == null)
            {
                commandClientId = Guid.NewGuid().ToString().ToUpper();
                session["commandClientId"] = commandClientId;
            }

            this.clientId = commandClientId.ToString();

            return result;
        }

        public ErrorMessage CreateErrorMessage(System.Exception e)
        {
            var result = new ErrorMessage();
            System.Exception cause = e;
            while (cause.InnerException != null)
            {
                cause = cause.InnerException;
            }

            result.faultDetail = cause.Message + "\r" + cause.StackTrace;
            result.faultCode = cause.GetType().FullName;
            result.faultString = cause.Message;
            result.rootCause = e.InnerException == null ? null : e.InnerException.Message + "\r" + e.InnerException.StackTrace;
            return result;
        }
    }
}
